<script setup>
import { useRouter } from 'vue-router';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import fullscreen from '../assets/fullscreen.svg?component'
import shutdown from '../assets/shutdown.svg?component'
import Calc from '../uilts/CalcAxisByAcrLength';
import Timer from '../uilts/AccurateTimer';
import { useTodoStore } from '../store/currentTodo'
import { useTimeStore } from '../store/time'
import { DoneTodo } from '../request/index'
import { useTodoListStore } from '../store/todoList'
let TodoStore = useTodoStore()
let TimeStore = useTimeStore()
let TodoList = useTodoListStore()
let Time = reactive({
    minute: '00',
    second: '00'
})
//start clock


//——timer animation
let globalRouter = useRouter();
let circleDom = ref(null)
let dashArray = ref(0) //圆形周长
let offset = ref(0) //进度条偏移
let title = ref("摸鱼")
let x = ref(192)    //小圆点的坐标
let y = ref(10)     //小圆点的坐标
let cx = 0      //circledom的圆心坐标
let r = 0       //circledom的半径
let recordTime = ref(0) //记录已经过时间
let TimerInstance;
let doneEvent = async () => {
    if (TimerInstance) {
        TimerInstance.stop()
        TimerInstance = null
    }

    Time.minute = '00'
    Time.second = '00'
    setPersent(100)
    try {
        let result = await DoneTodo()
        if (result && result.affected >= 1) {
            console.log('更新成功');
        } else {
            console.log('未更新')
        }
    } catch (e) {
        console.log(e)
    }

}
function doneTodo(){
    console.log(TodoStore.tid);
    TodoList.changeState(TodoStore.tid, '3')
    doneEvent()
}
function setPersent(persent) {
    if (circleDom.value) {
        circleDom.value.style.strokeDashoffset = dashArray.value - (persent / 100) * dashArray.value
        offset.value = circleDom.value.style.strokeDashoffset
    }
}
function setTitle(_title) {
    title.value = _title
}
function loadDOM() {
    dashArray.value = circleDom.value.getTotalLength()
    circleDom.value.style.strokeDasharray = dashArray.value
    cx = circleDom.value.getAttribute('cx')
    r = circleDom.value.getAttribute('r')

    TodoStore.$subscribe((mutation, state) => {
        if (!TimerInstance) {
            TimerInstance = startTodo({ second: 25 * 60 })
            setTitle(state.title)
        } else {
            doneEvent()
            TimerInstance = startTodo({ second: 25 * 60 })
        }

    })
}
function startTodo({ mode = "backward", second }) {
    let _Timer = Timer(mode, callPerSecond, second)
    _Timer.start()
    return _Timer
    function callPerSecond(remainTime, persent) {
        Time.minute = Math.floor(remainTime / 60)
        Time.second = remainTime % 60
        //更新进度条位置
        setPersent(persent * 100)
        recordTime.value += 1
        //更新小圆圈的位置
        let result = Calc(+offset.value.slice(0, -2), +r, cx)
        x.value = result.x
        y.value = result.y
        if (remainTime == 0 && mode == 'backward') {
            doneTodo()
        }
    }
}

function toPureMode() {
    if (TimerInstance) {
        TimeStore.startTime = TimerInstance.getStartTime()
        TimeStore.duration = TimerInstance.getDuration()
        TimeStore.second = TimerInstance.getSecond()
        globalRouter.push('/PureMode')
    }

}
onMounted(loadDOM)

</script>



<template>
    <div
        class="bg-white animate__animated animate__fadeIn rounded-3xl overflow-hidden pt-3 pb-10 px-5"
    >
        <header class="flex justify-between items-center">
            <div class="flex">
                <div class="w-2 self-stretch mr-2 my-2 rounded-xl bg-[#b2d9d6]"></div>
                <span class="text-3xl p-3 text-[#585858]">Timer</span>
            </div>
            <fullscreen @click="toPureMode()" />
        </header>
        <hr class="mt-1" />
        <main class="mt-6">
            <div class>
                <svg class="svg m-auto w-96 h-96 animate__bounceIn animate__animated">
                    <circle
                        r="182"
                        cy="192"
                        cx="192"
                        stroke-width="5"
                        stroke="#e6c7c2"
                        stroke-linejoin="round"
                        stroke-linecap="round"
                        fill="none"
                        ref="circleDom"
                        transform="matrix(0,-1,1,0,0,384)"
                        class="transition-all duration-500"
                    />
                    <circle
                        r="10"
                        :cy="y"
                        :cx="x"
                        stroke-linejoin="round"
                        stroke-linecap="round"
                        fill="#e6c7c2"
                        class="transition-all duration-200"
                    />
                    <text
                        x="192"
                        y="220"
                        fill="currentColor"
                        class="text-6xl number text-gray-600"
                        text-anchor="middle"
                        align-baseline="central"
                    >{{ Time.minute }}:{{ Time.second }}</text>
                </svg>

                <div class="text-center mt-5">
                    <div
                        class="bg-[#f2c2b8] absolute text-white px-5 py-3 text-lg font-semibold animate__animated animate__backInLeft"
                    >正在进行：{{ title }}</div>
                    <button class="w-14 m-auto h-14 bg-[#fbf2f1] rounded-full" @click="doneTodo()">
                        <shutdown
                            class="animate__animated animate__bounceInUp w-10 h-10 m-auto text-[#e6c7c2] hover:text-[#ce5551] transition"
                        />
                    </button>
                </div>
            </div>
        </main>
    </div>
</template>


<style>
.number {
    font-family: "MTC 7 Segment";
}
@font-face {
    font-family: "MTC 7 Segment";
    src: url("../assets/MTC-7-Segment.TTF");
}
/* svg { fill: currentColor; } */
</style>